package cn.haiway.drools.utils;

import com.sun.codemodel.JCodeModel;
import org.jsonschema2pojo.*;
import org.jsonschema2pojo.rules.RuleFactory;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author Haiway  on 2019/5/10
 */
public class JsonToPojoUtils {
    /***
     * JSON转JAVA类字符串
     * @param className JAVA类名
     * @param packageName 包名
     * @param json 需要转换的JSON字符串
     * @return JAVA文件内容字符串
     */
    public static String jsonToPojoString(String className, String packageName, String json) {
        JCodeModel codeModel = new JCodeModel();

        GenerationConfig config = new DefaultGenerationConfig() {
            @Override
            public boolean isGenerateBuilders() { // set config option by overriding method
                return true;
            }
        };

        SchemaMapper mapper = new SchemaMapper(new RuleFactory(config, new Jackson2Annotator(config), new SchemaStore()), new SchemaGenerator());
        try {
            mapper.generate(codeModel, className, packageName, json);
        } catch (IOException e) {
            e.printStackTrace();
        }
        File required = null;
        String javaFleString = "";
        try {
            //创建一个临时目录存储转换的JAVA文件
            required = Files.createTempDirectory("required").toFile();
            codeModel.build(required);
            String fileLocal = required.getPath() + "/" + packageName.replace(".", "/") + "/" + className + ".java";
            javaFleString = readFile(fileLocal, StandardCharsets.UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return javaFleString;
    }

    /***
     * 读取文件
     * @param path 文件路径
     * @param encoding 编码格式
     * @return 文件内容字符串
     * @throws IOException
     */
    public static String readFile(String path, Charset encoding)
            throws IOException {
        byte[] encoded = Files.readAllBytes(Paths.get(path));
        return new String(encoded, encoding);
    }
}
